package online.sharin.aix;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;

import android.speech.tts.Voice;
import android.view.View;

import java.util.Locale;

/**
 * 声明为public可以让activity包内的进行继承
 */
abstract public class BaseActivity extends AppCompatActivity {

    private TextToSpeech tts = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    /**
     * 弹出提示消息
     *
     * @param view       View
     * @param sequence   CharSequence 消息内容
     * @param actionText CharSequence 提示信息内容
     */
    protected void showMessage(View view, CharSequence sequence, CharSequence actionText) {
        Snackbar.make(view, sequence, Snackbar.LENGTH_SHORT).setAction(actionText, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        }).show();
    }

    protected void speakOut(CharSequence sequence) {

        getTextToSpeech().speak(sequence, TextToSpeech.QUEUE_ADD, null, "");
    }

    protected TextToSpeech getTextToSpeech() {
        if (null == tts) {
            tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int i) {
                    if (i == TextToSpeech.SUCCESS) {
                        if (TextToSpeech.LANG_AVAILABLE == tts.isLanguageAvailable(Locale.CHINA)) {
                            tts.setLanguage(Locale.CHINA);
                        } else {
                            tts.setLanguage(Locale.US);
                        }
                        // 设置音高0.3以下感觉是机器人语音
                        tts.setPitch(1.0f);
                        // 语速
                        tts.setSpeechRate(1.0f);
                        tts.setVoice(new Voice("Sarah", Locale.US, Voice.QUALITY_VERY_HIGH, Voice.LATENCY_VERY_HIGH, true, null));
                    }
                }
            });
        }
        return tts;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (tts != null) {
            tts.shutdown();
        }
    }
}
